from socket import *

from Config import getConfig

MaxBytes = 1024 * 1024


class mySocket:
    def __init__(self, host, port):
        try:
            self.tcpSerSock = socket(AF_INET, SOCK_STREAM)
            self.tcpSerSock.connect((host, port))
        except Exception as e:
            print(e)
            print("连接服务器失败,请检查服务器是否开启")
            print(host, ':', port)
            exit()

    def socketclose(self):
        self.tcpSerSock.close()
        pass

    def socketSend(self, data: bytearray, com):
        arrBuf = bytearray(b'\xff\xaa\xff' + com.to_bytes(1, byteorder='little'))
        arrBuf += bytearray(len(data).to_bytes(4, byteorder='little'))
        arrBuf += bytearray(int(getConfig('client.config', 'all', 'guid')).to_bytes(64, byteorder='little'))
        arrBuf += data
        self.tcpSerSock.sendall(arrBuf)
        # print(arrBuf)
        return

    def socketReceive(self):
        receiveData = self.tcpSerSock.recv(MaxBytes)
        comIndex = receiveData.find(b'\xff\xaa\xff')
        com = receiveData[comIndex + 3]
        dataSize = int.from_bytes(receiveData[comIndex + 4:comIndex + 8], 'little')
        guid = int.from_bytes(receiveData[comIndex + 8:comIndex + 72], 'little')
        data = receiveData[comIndex + 72:comIndex + 72 + dataSize]
        return com, dataSize, guid, data

    def closeSocket(self):
        self.tcpSerSock.close()
